<template>
    <div class="container">
        <div class="content_wrapper">
            <div class="lyecs-form-table">
                <el-form v-if="!loading" ref="formRef" :rules="rules" :model="formState" label-width="auto">
                    <el-form-item v-if="formState.is_new_user != 0" prop="coupon_type" label="优惠券类型">
                        <RadioType
                            v-model:modelValue="formState.coupon_type"
                            :radioList="[
                                { key: 1, title: '满减券', desc: '例：满100减20' },
                                { key: 2, title: '折扣券', desc: '例：满100打8折' }
                            ]"
                        >
                        </RadioType>
                    </el-form-item>
                    <el-form-item prop="coupon_name" label="优惠券名称">
                        <el-input type="text" maxlength="60" v-model="formState.coupon_name" style="width: 300px;" />
                    </el-form-item>
                    <el-form-item prop="reduce_type" label="优惠内容">
                        <div class="tig-radio">
                            <el-radio-group v-model="formState.reduce_type">
                                <div class="flex mb20">
                                    <el-radio :value="1"></el-radio>
                                    <div class="flex">
                                        <p class="mr10">满</p>
                                        <div class="check-box">
                                            <el-input v-model="formState.min_order_amount" class="mr10" style="width: 240px;" :disabled="formState.reduce_type == 2">
                                                <template #append>
                                                    <div class="flex" v-if="formState.reduce_type != 2">
                                                        <div class="ml10 item" :class="{'active': formState.coupon_unit == 1}" @click="formState.coupon_unit = 1">元</div>
                                                        <div class="ml10 item" :class="{'active': formState.coupon_unit == 2}" @click="formState.coupon_unit = 2">件</div>
                                                    </div>
                                                    <div class="flex disabled" v-else>
                                                        <div class="ml10 item" :class="{'active': formState.coupon_unit == 1}">元</div>
                                                        <div class="ml10 item" :class="{'active': formState.coupon_unit == 2}">件</div>
                                                    </div>
                                                </template>
                                            </el-input>
                                        </div>
                                        <p class="mr10">, {{ formState.coupon_type == 1 ? "减" : "打"}}</p>
                                        <el-input v-if="formState.coupon_type == 1" v-model="formState.coupon_money" style="width: 180px;" :disabled="formState.reduce_type == 2">
                                            <template #append>元</template>
                                        </el-input>
                                        <el-input v-if="formState.coupon_type == 2" v-model="formState.coupon_discount" style="width: 180px;" :disabled="formState.reduce_type == 2">
                                            <template #append>折</template>
                                        </el-input>
                                    </div>
                                </div>
                                <div class="flex mb20">
                                    <el-radio :value="2"></el-radio>
                                    <div class="flex">
                                        <p class="mr10">无门槛, {{ formState.coupon_type == 1 ? "减" : "打"}}</p>
                                        <el-input v-if="formState.coupon_type == 1" v-model="formState.coupon_money" style="width: 180px;" :disabled="formState.reduce_type == 1">
                                            <template #append>元</template>
                                        </el-input>
                                        <el-input v-if="formState.coupon_type == 2" v-model="formState.coupon_discount" style="width: 180px;" :disabled="formState.reduce_type == 1">
                                            <template #append>折</template>
                                        </el-input>
                                    </div>
                                </div>
                            </el-radio-group>
                        </div>
                    </el-form-item>
                    <el-form-item prop="max_order_amount" label="优惠上限" v-if="formState.coupon_type == 2">
                        <div>
                            <div>
                                <el-input v-model="formState.max_order_amount" style="width: 180px;">
                                    <template #append>元</template>
                                </el-input>
                            </div>
                            <div class="extra">最多可打折的金额, 默认 0 表示无限制</div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="send_type" label="用券时间">
                        <div class="tig-radio">
                            <el-radio-group v-model="formState.send_type">
                                <div class="flex mb20">
                                    <el-radio :value="1"></el-radio>
                                    <div class="flex flex-align-center">
                                        <SelectTimeInterval
                                            v-model:end-date="formState.use_end_date"
                                            v-model:start-date="formState.use_start_date"
                                            :clearable="true"
                                            width="180px"
                                            type="datetime"
                                            value-format="YYYY-MM-DD HH:mm:ss"
                                            :disabled="formState.send_type == 0"
                                        ></SelectTimeInterval>
                                        <div>
                                            <el-radio-group class="itemWidth" v-model="date_type" @change="changeDateType" :disabled="formState.send_type == 0">
                                                <el-radio-button :value="0">1天</el-radio-button>
                                                <el-radio-button :value="1">7天</el-radio-button>
                                                <el-radio-button :value="2">15天</el-radio-button>
                                            </el-radio-group>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex mb20">
                                    <el-radio :value="0"></el-radio>
                                    <div class="flex">
                                        <p class="mr10">领券后</p>
                                        <el-input v-model="formState.delay_day" style="width: 100px;" :disabled="formState.send_type == 1">
                                        </el-input>
                                        <p class="mr10 ml10"> , 有效期</p>
                                        <el-input v-model="formState.use_day" style="width: 180px;" :disabled="formState.send_type == 1">
                                            <template #append>天</template>
                                        </el-input>
                                    </div>
                                </div>
                            </el-radio-group>
                            <div class="extra" v-if="formState.send_type == 0">领券后默认0天生效, 表示立即生效</div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="send_num" label="发放总量">
                        <div>
                            <div>
                                <el-input v-model="formState.send_num" style="width: 180px;">
                                    <template #append>张</template>
                                </el-input>
                            </div>
                            <div class="extra">修改优惠券总量时只能增加不能减少，请谨慎设置。</div>
                        </div>
                    </el-form-item>
                    <el-form-item  prop="limit_num" label="领取次数限制">
                        <div>
                            <div>
                                <el-input :disabled="formState.is_new_user == 1" v-model="formState.limit_num" style="width: 180px;">
                                    <template #append>次</template>
                                </el-input>
                            </div>
                            <div class="extra">{{formState.is_new_user == 1?'新人专享券仅限领取一次':'限制每个用户最多可领次数, 默认 0 表示无限制'}}</div>
                        </div>
                    </el-form-item>
                    <el-form-item v-if="formState.is_new_user == 1" prop="is_new_user" label="领取客户限制">
                        <div v-if="formState.is_new_user == 1">新人专享</div>
                    </el-form-item>
                    <el-form-item v-if="formState.is_new_user == 2" prop="limit_user_rank" label="领取客户限制">
                        <el-select
                            v-model="formState.limit_user_rank"
                            multiple
                            placeholder="请选择"
                            style="width: 300px"
                            clearable
                            >
                            <el-option
                                v-for="item in rankList"
                                :key="item.rank_id"
                                :label="item.rank_name"
                                :value="item.rank_id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="send_range" label="适用商品">
                        <div>
                            <div>
                                <SelectGoodsRange
                                    v-model:rangeIds="formState.send_range_data"
                                    v-model:rangeType="formState.send_range"
                                    :justProudct="true"
                                />
                            </div>
                            <div v-if="Number(formState.send_range) > 0 && !is_product" class="extra red">请选择商品</div>
                        </div>
                    </el-form-item>
                    <!-- <el-form-item prop="is_global" label="全店展示">
                        <div>
                            <el-radio-group v-model="formState.is_global" @change="onChangeIsGlobal">
                                <el-radio :value="1">是</el-radio>
                                <el-radio :value="0">否</el-radio>
                            </el-radio-group>

                        </div>
                    </el-form-item> -->
                    <el-form-item prop="is_show" label="是否展示">
                        <div>
                            <el-radio-group v-model="formState.is_show">
                                <el-radio :value="1">是</el-radio>
                                <el-radio :value="0">否</el-radio>
                            </el-radio-group>
                        </div>
                    </el-form-item>
                    <el-form-item prop="coupon_desc" label="券使用说明">
                        <el-input type="textarea" :row="6" v-model="formState.coupon_desc" style="width: 300px;"/>
                    </el-form-item>
                    <el-form-item v-show="!props.isDialog" :wrapper-col="{ offset: 4, span: 16 }">
                        <el-button ref="submitBtn" class="form-submit-btn" type="primary" @click="onSubmit()">提交</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, shallowRef, onMounted, reactive } from "vue";
import RadioType from "@/components/radio/src/RadioType.vue";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import type { CouponFormState, CouponRankList } from "@/types/promotion/coupon.d";
import { getCoupon, updateCoupon, getCouponConfig } from "@/api/promotion/coupon";
import type { FormInstance, FormRules } from "element-plus";
import { SelectGoodsRange } from "@/components/select";
import { SelectTimeInterval } from "@/components/select";
import { getDays } from "@/utils/util";
import { formattedDate } from "@/utils/time";
const emit = defineEmits(["submitCallback", "update:confirmLoading", "close"]);

const rankList = ref<CouponRankList[]>([]); // 允许领取客户等级列表
const props = defineProps({
    id: {
        type: Number,
        default: 0
    },
    coupon_type: {
        type: Number,
        default: 0
    },
    is_new_user: {
        type: Number,
        default: 0
    },
    act: {
        type: String,
        default: ""
    },
    isDialog: {
        type: Boolean,
        default: false
    }
});
const loading = ref<boolean>(true);
const query = useRouter().currentRoute.value.query;
const action = ref<string>(props.isDialog ? props.act : String(query.act));
const id = ref<number>(props.isDialog ? props.id : Number(query.id));
const coupon_type = ref<number>(props.isDialog ? props.coupon_type : Number(query.coupon_type));
const is_new_user = ref<number>(props.isDialog ? props.is_new_user : Number(query.is_new_user));
const operation = action.value === "add" ? "create" : "update";
const formRef = shallowRef();
const formState = ref<CouponFormState>({
    send_range: 0,
    send_range_data: [],
    is_global: 0,
    is_show: 1,
    coupon_type: coupon_type.value || 1,
    is_new_user: is_new_user.value || 0,
    coupon_unit: 1,
    reduce_type: 1,
    send_type: 1,
    limit_user_rank: [],
    use_start_date: formattedDate(new Date(), "YYYY-MM-DD HH:mm:ss"),
    use_end_date: formattedDate(getDays(1, "add"), "YYYY-MM-DD HH:mm:ss"),
    delay_day:0,
    send_num: 1000,
    coupon_money: 20,
    coupon_discount: 8,
    min_order_amount: 100,
    max_order_amount: 0,
    limit_num: is_new_user.value==1?1:0
});
const is_product = ref<boolean>(true)
const date_type = ref(0)
const changeDateType = (event: number) => {
    formState.value.use_start_date = formattedDate(new Date(), "YYYY-MM-DD HH:mm:ss");
    if (event === 0) {
        //1
        formState.value.use_end_date = formattedDate(getDays(1, "add"), "YYYY-MM-DD HH:mm:ss");
    }
    if (event === 1) {
        //7
        formState.value.use_end_date = formattedDate(getDays(7, "add"), "YYYY-MM-DD HH:mm:ss");
    }
    if (event === 2) {
        //15
        formState.value.use_end_date = formattedDate(getDays(15, "add"), "YYYY-MM-DD HH:mm:ss");
    }
};
onMounted(() => {
    if (action.value === "detail") {
        // 获取详情数据
        fetchCoupon();
    } else {
        loading.value = false;
    }
    fetchCouponConfig()
});
const fetchCoupon = async () => {
    try {
        const result = await getCoupon(action.value, {
            id: id.value,
            coupon_type: coupon_type.value,
            is_new_user: is_new_user.value
        });
        Object.assign(formState.value, result.item);
    } catch (error: any) {
        message.error(error.message);
        emit("close");
    } finally {
        loading.value = false;
    }
};
const fetchCouponConfig = async () => {
    try {
        const result = await getCouponConfig();
        rankList.value = result.rank_list;
    } catch (error: any) {
        message.error(error.message);
    } finally {
        loading.value = false;
    }
};

const onChangeIsGlobal = (value: number) => {
    if (value == 1) {
        formState.value.send_range = 0;
    }
};
// 表单通过验证后提交
const onSubmit = async () => {
    if(!validateProduct()){
        return
    }
    await formRef.value.validate();
    try {
        emit("update:confirmLoading", true);
        const result = await updateCoupon(operation, { id: id.value, ...formState.value });
        emit("submitCallback", result);
        message.success(result.message);
    } catch (error: any) {
        message.error(error.message);
    } finally {
        emit("update:confirmLoading", false);
    }
};
// 表单提交
const onFormSubmit = () => {
    onSubmit();
};
const validateReduce = (rule: any, value: any, callback: any) => {
    if (formState.value.reduce_type == 1) {
        if(formState.value.coupon_type == 1 && (Number(formState.value.min_order_amount) <= 0 || Number(formState.value.coupon_money) <= 0)){
            callback(new Error("请填写"));
            return
        }
        if(formState.value.coupon_type == 2 && (Number(formState.value.min_order_amount) <= 0 || Number(formState.value.coupon_discount) <= 0)){
            callback(new Error("请填写"));
            return
        }
        callback();
    } else if (formState.value.reduce_type == 2) {
        if(formState.value.coupon_type == 1 && Number(formState.value.coupon_money) <= 0){
            callback(new Error("请填写"));
            return
        }
        if(formState.value.coupon_type == 2 && Number(formState.value.coupon_discount) <= 0){
            callback(new Error("请填写"));
            return
        }
        callback();
    }
};
const validateSendTime = (rule: any, value: any, callback: any) => {
    if (formState.value.send_type == 1) {
        if(!formState.value.use_start_date && !formState.value.use_end_date){
            callback(new Error("请输入用券时间"));
            return
        }
        callback();
    } else if (formState.value.send_type == 0) {
        if(!formState.value.delay_day && !formState.value.use_day){
            callback(new Error("请输入用券时间"));
            return
        }
        callback();
    } else {
        callback();
    }
}
const validateProduct = () => {
    if(Number(formState.value.send_range) > 0 && formState.value.send_range_data.length == 0){
        is_product.value = false;
    }else{
        is_product.value = true;
    }
    return is_product.value
};

interface RuleForm {
    coupon_name: string;
    reduce_type: number;
    send_type: number;
    send_num: number;
    limit_num: number;
    limit_user_rank: number[];
}
const rules = reactive<FormRules<RuleForm>>({
    coupon_name: [{ required: true, message: "请输入优惠券名称", trigger: "blur" }],
    reduce_type: [{ required: true,  validator: validateReduce, trigger: "blur" }],
    send_type: [{ required: true,  validator: validateSendTime, trigger: "blur" }],
    send_num: [{ required: true, message: "请填写发放总量", trigger: "blur" }],
    limit_num: [{ required: true, message: "请设置领取次数", trigger: "blur" }],
    limit_user_rank: [{ required: true, message: "请选择可用会员等级", trigger: "blur" }],
});
defineExpose({ onFormSubmit });
</script>
<style lang="less" scoped>
.container{
    .tig-radio{
        :deep(.el-radio-group){
            display: block;
            font-size: 12px;
        }
        :deep(.el-radio){
            margin-right: 0px;
        }
        .check-box{
            cursor: pointer;
            :deep(.el-input-group__append){
                background-color: #fff !important;
                padding: 0;
                box-shadow: none;
            }
            .item{
                width: 35px;
                height: 25px;
                line-height: 25px;
                text-align: center;
                border: 1px solid #b8b8b8;
            }
            .active{
                border: 1px solid var(--tig-primary);
                color: var(--tig-primary);
                background-color: #e6efff;
            }
            .disabled{
                .item{
                    background-color: #f7f7f7;
                    color: #ccc;
                }
                .active{
                    border: 1px solid #b8b8b8;
                    background-color: #e0e0e0;
                }
            }
        }
    }
    .itemWidth{
        margin-bottom: 3px;
        margin-left: 10px;
    }
    .red{
        color: var(--el-color-danger);
    }

}
</style>
